package com.gedi.powergrid.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class EchoClient {

    private int port;

    private String host;

    public EchoClient(String host, int port) {
        this.port = port;
        this.host = host;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        Bootstrap bs = new Bootstrap();
        bs.group(bossGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new EchoClientInboundHandler());
                    }
                });
        // 客户端开启
        Channel channel = bs.connect(host, port).sync().channel();


        channel.writeAndFlush(Unpooled.copiedBuffer("hello ".getBytes()));

        channel.closeFuture().sync();
        System.out.println("finish");
    }

    public static void main(String[] args) throws Exception {
        new EchoClient("localhost", 8080).run();
    }
}
